﻿using Furion;
using Furion.DatabaseAccessor.Extensions;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.JsonSerialization;
using iemtm.WeChat.Application.Common.Dtos;
using iemtm.WeChat.Application.UserCenter;
using iemtm.WeChat.Core;
using iemtm.WeChat.Core.Extension;
using iemtm.WeChat.Core.Extension.Helper;
using iemtm.WeChat.Core.Managers;
using iemtm.WeChat.Core.Util;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace iemtm.WeChat.Application.GenCenter
{
    [Route("api/[controller]")]
    public class GeneratorAppService : IGeneratorAppService, IDynamicApiController, ITransient
    {

        private readonly IWorkManager _workManager;
        private readonly IUserManager _userManager;
        private readonly IGeneratorManager _generatorManager;
        private readonly IInfoManager _infoManager;
        
        public GeneratorAppService(IWorkManager workManager
            , IUserManager userManager
            , IGeneratorManager generatorManager
            , IInfoManager infoManager
            )
        {
            _workManager = workManager;
            _userManager = userManager;
            _generatorManager = generatorManager;
            _infoManager = infoManager;
        }
        /// <summary>
        /// 油机列表
        /// </summary>
        /// <param name="rows">最后一条数据id</param>
        /// <param name="order">排序</param>
        /// <param name="page">页数</param>
        /// <param name="limit">每页显示数量</param>
        /// <returns></returns>
        [QueryParameters]
        public dynamic GetGenList(int rows, string order, int page, int limit)
        {

            
                //UserAccountWxModel loginfo = GetLoginInfoWx.Get(LoginInfo.UserCode);
                var loginfo = _workManager.CurrentUser;
                //项目筛选

                List<Generator> genlist0 = MemoryEntity.gBuffGen.All.Values.Where(gen => gen.PrjCode == loginfo.PrjCode).ToList();

                //区域筛选
                
                List<string> vas = loginfo.VisibleArea.Split(',').ToList();
                if (vas == null || vas.Count <= 0) genlist0 = null;
                List<Generator> genlist = new List<Generator>();
                if (genlist0 != null)
                    foreach (Generator gg in genlist0)
                    {
                        foreach (string ii in vas)
                            if (gg.AreaCode.StartsWith(ii)) { genlist.Add(gg); break; }
                    }
                //公司筛选
                bool CommonFilterJustByArea = loginfo.PerUrls.Contains("/DataPermission/CommonFilterJustByArea");
                if (!CommonFilterJustByArea && genlist != null)
                    genlist = genlist.Where(gen => gen.CompanyCode.StartsWith(loginfo.CompanyCode)).ToList();

            iemtm.WeChat.Core.Util.Common.ComputeGensStatus(genlist);
                //开始分页
                var genlistdata = genlist.OrderBy(u => u.GeneratorId).Select(gen => new
                {
                    GeneratorId = gen.GeneratorId,
                    BOnline = gen.BOnline,
                    Status = gen.Status,
                    ComputedStatus = gen.ComputedStatus,
                    GensetNum = gen.GensetNum,
                    name = gen.GensetNum,
                    label = gen.GensetNum,
                    DTUID = gen.DTUID ?? "0",//gen.DTUID,
                    IsIdle = gen.IsIdle,
                    Alarm = gen.Alarms
                });
                switch (rows)
                {
                    case 0: break;
                    case 1: genlistdata = genlistdata.Where(c => c.ComputedStatus == 1 && c.BOnline == true); break;
                    case 3: genlistdata = genlistdata.Where(c => c.ComputedStatus == 3); break;
                    case 5: genlistdata = genlistdata.Where(c => c.ComputedStatus == 5); break;
                    case 4: genlistdata = genlistdata.Where(i => i.DTUID.ToUpper().Contains(order.ToUpper()) || i.GensetNum.ToUpper().Contains(order.ToUpper())); break; //查询
                };
                return new
                {
                    total = genlistdata.Count(),
                    data = genlistdata.Skip((page - 1) * limit).Take(limit)
                };
            
            
        }

        /// <summary>
        /// 油机实时监控
        /// </summary>
        /// <param name="dtuId">dtuId</param>
        /// <returns></returns>
        [QueryParameters]
        [HttpGet]
        public async Task<dynamic> realData(string dtuId)
        {
            
                //Collector cc = JsonConvert.DeserializeObject<Collector>(jstr.str);
                //string dtuId = cc != null ? cc.DTUID : "";
                if (dtuId == null || dtuId == "")
                    return null;


                Generator g = MemoryEntity.gBuffGen[dtuId];// GeneratorList.Frist(dtuId);
                //Collector c = g != null && !string.IsNullOrEmpty(g.DTUID) ? BllHelper.cBuff[g.DTUID] : BllHelper.cBuff[dtuId];

                Collector c = MemoryEntity.cBuffColl[dtuId];//CollectorList.Frist(dtuId);

                if (c == null)
                    return null;

                //如果采集器离线，显示最后一次运行的电参量
                if (!c.BOnline.Value)
                {
                    
                    DateTime dtNow = DateTime.Now;
                    DateTime dtS = dtNow - new TimeSpan(30, 0, 0, 0);
                    ReportRecord rptR =await _generatorManager.GetReportRecordFirstAsync(1, dtuId, dtS, dtNow);

                    if (rptR != null)
                    {
                        c.GENVOLTL1 = rptR.GENVOLTL1;
                        c.GENVOLTL2 = rptR.GENVOLTL2;
                        c.GENVOLTL3 = rptR.GENVOLTL3;

                        c.GENCURRENTL1 = rptR.GENCURRENTL1;
                        c.GENCURRENTL2 = rptR.GENCURRENTL2;
                        c.GENCURRENTL3 = rptR.GENCURRENTL3;

                        c.GENFREQ = rptR.GENFREQ;
                        c.ACTIVEPOWER = rptR.ACTIVEPOWER / 1000;
                    }
                }

                //if (c != null)
                //    c.DATECLOCK = DateTime.Now;
                if (c != null && c.CurDevServer != null && c.CurDevServer != "")
                {
                    // MsgSender.instance.SendAsync(c.CurDevServer, "realMonitor", dtuId);
                    TcpCommunication.realMonitor(dtuId);
                }
                //CollectorViewMode cvm = new CollectorViewMode();
                //CollectorViewMode cvm = MapperHelper.Mapper<CollectorViewMode, Collector>(c);
                // CopyPdfEn(c, cvm);
                if (c.GenStart == null || c.GenStop == null)
                {
                    c.EmptyLoadPeriod = null;
                }
                else
                {
                    TimeSpan ts = c.GenStop.Value - c.GenStart.Value;
                    c.EmptyLoadPeriod = (decimal)((decimal)(ts.TotalSeconds / 3600) - c.RunningPeriod);
                    c.EmptyLoadPeriod = c.EmptyLoadPeriod < 0 ? 0 : c.EmptyLoadPeriod;
                }

                //  return new { c = BllHelper.ToDynamicPdfEn(cvm), g = g != null ? BllHelper.ToDynamicPdfEn(g) : null };
                return new { c = c, g = g != null ? g : null };
            
           

        }

        ///// <summary>
        ///// 对油机状态根据优先级进行状态合并
        ///// 无采集器>运行中>需维修>需保养>正常
        ///// </summary>
        ///// <param name="gens"></param>
        //private void ComputeGensStatus(List<Generator> gens)
        //{

        //    foreach (Generator gen in gens)
        //    {
        //        //运行中
        //        if ( (gen.bRunning!=null&&gen.bRunning.Value) || gen.Status == 1)
        //        {
        //            gen.ComputedStatus = 1;
        //        }
        //        //无采集器
        //        else if (string.IsNullOrEmpty(gen.DTUID) || gen.Status == 2)
        //        {
        //            gen.ComputedStatus = 2;
        //        }
        //        //需维修
        //        else if ( (gen.NeedRepaired!=null&&gen.NeedRepaired.Value) || gen.Status == 3)
        //        {
        //            gen.ComputedStatus = 3;
        //        }
        //        //需保养    
        //        else if (gen.NeedMaintenance == true || gen.Status == 4)
        //        {
        //            gen.ComputedStatus = 4;
        //        }
        //        //正常
        //        else
        //        {
        //            gen.ComputedStatus = 5;
        //        }
        //    }
        //}


        /// <summary>
        /// 添加油机
        /// </summary>
        /// <param name="GensetNum"></param>
        /// <param name="DTUID"></param>
        /// <param name="DTUSIM"></param>
        /// <param name="CompanyCode"></param>
        /// <param name="FACCODE"></param>
        /// <returns></returns>
        [HttpGet]
        [QueryParameters]
        public async Task<dynamic> AddGen(string GensetNum, string DTUID, string DTUSIM, string CompanyCode, string FACCODE)
        {
            int code = 0;
            string result = "";
            try
            {
                var model = new Generator()
                {
                    GensetNum = GensetNum,
                    DTUID = DTUID,
                    DTUSIM = DTUSIM,
                    CompanyCode = CompanyCode,
                    FACCODE = FACCODE
                };

                var loginfo = _workManager.CurrentUser;

                if (loginfo == null) return new { code = 0, result = "请重新登录系统！" };

                Company company = await _infoManager.GetCompanyByCodeAsync(CompanyCode);// dbContext.Queryable<Company>().First(u => u.CompanyCode == model.CompanyCode);
                Area area = company == null ? null : await _infoManager.GetAreaByCodeAsync(company.AreaCode);
                if (area == null)
                    return new { code = 0, result = "请选择所属公司！" };
                model.AreaId = area.AreaId;
                model.AreaCode = area.AreaCode;
                model.AreaName = area.AreaName;
                model.PrjCode = loginfo.PrjCode;
                model.PrjName = loginfo.PrjName;
                model.BEdited = true; //新增油机是默认为需要同步
                model.IsIdle = true; //默认为闲置
                model.Status = 5;//待用
                model.IsFixedSetup = true;//默认为661 固定油机
                model.bRunning = false;
                model.GeneratorCode = _generatorManager.MakeGeneratorCode(loginfo.PrjCode);
                if (string.IsNullOrEmpty(model.GeneratorCode))
                    return new { code = 0, result = "产生油机内部编号失败！" };


                Generator gExist = MemoryEntity.gBuffGen.All.Values.FirstOrDefault(u => u.GensetNum == model.GensetNum);

                if (gExist != null)
                    return new { code = 0, result = "油机编号已被使用！" };

                #region 判断采集器是否被使用过，或新增采集器
                if (!string.IsNullOrEmpty(model.DTUID))
                {
                    //List<Generator> gListTmp =
                    //    (from ii in BllHelper.gBuff.All.Values where ii.DTUID != null && ii.DTUID == model.DTUID select ii)
                    //        .ToList();
                    List<Generator> gListTmp = MemoryEntity.gBuffGen.All.Values.Where(ii => ii.DTUID != null && ii.DTUID == model.DTUID).ToList();
                    if (gListTmp != null && gListTmp.Count > 0)
                        return new { code = 0, result = "采集器已被其它油机使用！" };
                    else
                    {
                        //添加采集器
                        //Collector c = new Collector();
                        //c.DTUID = model.DTUID;
                        //c.AreaId = model.AreaId;
                        //c.AreaCode = model.AreaCode;
                        //c.AreaName = model.AreaName;
                        //c.PrjCode = model.PrjCode;
                        //c.PrjName = model.PrjName;
                        //c.GensetNum = model.GensetNum;
                        //c.DTUID = model.DTUID;
                        //c.CompanyCode = model.CompanyCode;
                        //c.FACCODE = model.FACCODE;
                        
                        var c = model.Adapt<Collector>();
                        c.BOnline = false;
                        if (MemoryEntity.cBuffColl[DTUID] == null)
                        {

                            var TempEntity = await _generatorManager.AddCollectorAsync(c);
                            if (TempEntity != null) MemoryEntity.cBuffColl.Update(TempEntity);
                        }
                        else
                        {
                            var TempEntity = await _generatorManager.UpdateCollectorAsync(c);
                        }
                    }

                }
                #endregion

                //添加model到数据库
                //code = BllHelper.dbCxt.Add<Generator>(model);
                // code = dbContext.Insertable(model).ExecuteCommand();
                var resultModel = await _generatorManager.AddGeneratorAsync(model);
                if (resultModel != null)
                {
                    code = 1;
                    MemoryEntity.gBuffGen.Update(resultModel);

                    result = "添加成功!"; //如果大于0则表示添加成功，否则添加失败
                                      //更新缓存  http://172.16.0.12/
                    WebApiCommunication.AddGenWXCacaht(GensetNum, DTUID);
                }
                else
                {
                    result = "添加失败!";
                }


                return new { code, result };
            }
            catch (Exception ex)
            {
                result = result+ex.Message;
                return new { code, result };
            }

        }


        /// <summary>
        /// 删除机组
        /// </summary>
        /// <param name="GeneratorId"></param>
        /// <returns></returns>
        [QueryParameters]
        [HttpGet]
        public async Task<ResultModel> DeleteGen(int GeneratorId)
        {
            var result = await WebApiCommunication.DeleteGen(GeneratorId.ToString());
            var resultmodel=  JSON.GetJsonSerializer().Deserialize<ResultModel>(result);
            if (resultmodel.Code > 0)
            {
               var T= MemoryEntity.gBuffGen.All.Values.FirstOrDefault(u => u.GeneratorId == GeneratorId);
                if (T != null) MemoryEntity.gBuffGen.Remove(T);
            }
            return resultmodel;

        }

        /// <summary>
        /// 通过发电机或者DTU查询相关记录
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [QueryParameters]
        public ResultModel GetDtuIdByGenOrDtu(string id)
        {
            var loginfo = _workManager.CurrentUser;
            ResultModel result = new ResultModel() { Code = 0 };
            var geninfo =MemoryEntity.gBuffGen.All.Values.Where(c => c.DTUID == id || c.GensetNum == id).Where(c => c.PrjCode == loginfo.PrjCode);
            if (geninfo.Count() == 0)
            {
                result.Code = -1;//未查询到油机信息
            }
            else
            {
                result.Code = geninfo.Count();
                List<GenSelectModel> genlist = new List<GenSelectModel>();
                foreach (var item in geninfo)
                {
                    var dtuid = "";
                    if (item.DTUID != null)
                    {
                        dtuid = item.DTUID.Length == 15 ? item.DTUID : null;//判断DTU合法性
                    }
                    genlist.Add(new GenSelectModel { GeneratorId = item.GeneratorId, GensetNum = item.GensetNum, GeneratorCode = item.GeneratorCode, DTUID = dtuid, IsFixedSetup = item.IsFixedSetup!=null? item.IsFixedSetup.Value :false});
                }
                result.Result = genlist;
            }
            return result;
        }


        /// <summary>
        /// 自检
        /// </summary>
        /// <param name="dtuId"></param>
        /// <returns></returns>
        /// 
        [HttpGet]
        [QueryParameters]
        public async Task<dynamic> GetSelfCheckInfoByDtuId(string dtuId)
        {
            return await _generatorManager.GetSelfCheckInfoByDtuId(dtuId,_workManager.CurrentUser.PrjCode);
        }

        #region 采集器 保养-与图片

        /// <summary>
        /// 获取油机维修列表数量
        /// </summary>
        /// <param name="times">全部0 一周7 半月15 本月30</param>
        /// <param name="paraStr">搜索</param>
        /// <returns></returns>
        [QueryParameters]
        [HttpGet]
        public dynamic GetGenMainCount(int times, string paraStr)
        {
            try
            {
               
                var loginfo = _workManager.CurrentUser;
                if (loginfo == null)
                    return null;
                var whereStr = 0;
                if (paraStr != "" && paraStr != null)
                    whereStr = 1;//搜索框有内容
                var whereStr2 = (whereStr == 1) ? (" and (al.GensetNum like '%" + paraStr + "%' or DTUID like '%" + paraStr + "%' )") : "";
                if (times == 1)//今天
                {
                    whereStr2 += (" and al.MaintDate BETWEEN CONVERT(varchar(100), GETDATE(), 23) +' 00:00:00' AND CONVERT(varchar(100), GETDATE(), 23) +' 23:59:59' ");
                }
                else if (times == 7)//7天内
                {
                    whereStr2 += (" and DateDiff(dd,al.MaintDate,getdate())<=7  ");
                    //whereStr2 = " and al.ExecutionDate>=(select dateadd(day,-7,(select CONVERT(varchar(30),GETDATE(),23)))) and al.ExecutionDate<=(select CONVERT(varchar(30),GETDATE(),23)+' 23:59:59') and (al.BaseStation like '%" + paraStr + "%' or al.JobNumber like '%" + paraStr + "%' or al.AnnounceCode like '%" + paraStr + "%')";
                }
                else if (times == 30)//本月
                {
                    whereStr2 += (" and  DateDiff(dd,al.MaintDate,getdate())<=30 ");
                }
                bool commonFilterJustByArea = loginfo.PerUrls.Contains("/DataPermission/CommonFilterJustByArea");
                string filterCompanyCode = " and al.areaCode like '" + loginfo.AreaCode + "%'";
                // var isAudit = loginfo.PerUrls.Contains("/Gen/AnnounceTeleAudit/Audit");
                string sqlstr = "";
                //所有
                DataTable notExeDt = new DataTable();
                //待审核
                DataTable exeingDt = new DataTable();
                //审核通过
                DataTable completeDt = new DataTable();
                //审核不通过
                DataTable audiuDt = new DataTable();






                sqlstr = $" SELECT COUNT(MaintId) as count FROM Maintenence AS al where  al.PrjCode={loginfo.PrjCode}  {filterCompanyCode}  {whereStr2} ";
                //所有 
                notExeDt = (sqlstr + "").SqlQuery();

                //待审核  
                exeingDt = (sqlstr + " and IsAudited is null").SqlQuery();

                //审核通过
                completeDt = (sqlstr + " and IsAudited=1 ").SqlQuery();

                //审核不通过
                audiuDt = (sqlstr + " and IsAudited=0 ").SqlQuery();

                return new
                {

                    noExtTotal = notExeDt.Rows[0]["count"],
                    exingTotal = exeingDt.Rows[0]["count"],
                    completelyTotal = completeDt.Rows[0]["count"],
                    audiuTotal = audiuDt.Rows[0]["count"],

                };
            }
            catch (Exception ex)
            {
               
                return new ResultModel() { Code = 0, Result = "会话过期" +ex.Message };

            }
        }

        /// <summary>
        /// 获取油机保养列表（分页）
        /// </summary>
        /// <param name="times">全部0 一周7 半月15 本月30</param>
        /// <param name="pagesize">每页多少数据，默认50</param>
        /// <param name="topNum">配合sql语句</param>
        /// <param name="menuIndex">页面tab选项 0：所有 1：待审核 2：审核通过 3：审核不通过</param>
        /// <param name="paraStr">查询条件</param>
        /// <returns></returns>
        [HttpGet]
        [QueryParameters]
        public dynamic GetGenMainListByPage(int times, int pagesize, int topNum, int menuIndex, string paraStr)
        {
            try
            {
                var loginfo =_workManager.CurrentUser;
                if (loginfo == null)
                    return null;
                var whereStr = 0;
                if (paraStr != "" && paraStr != null)
                    whereStr = 1;//搜索框有内容
                var whereStr2 = (whereStr == 1) ? (" and (al.GensetNum like '%" + paraStr + "%' or DTUID like '%" + paraStr + "%' )") : "";
                if (times == 1)//今天
                {
                    whereStr2 += (" and al.MaintDate BETWEEN CONVERT(varchar(100), GETDATE(), 23) +' 00:00:00' AND CONVERT(varchar(100), GETDATE(), 23) +' 23:59:59' ");
                }
                else if (times == 7)//7天内
                {
                    whereStr2 += (" and DateDiff(dd,al.MaintDate,getdate())<=7  ");
                }
                else if (times == 30)//本月
                {
                    whereStr2 += (" and  DateDiff(dd,al.MaintDate,getdate())<=30 ");
                }
             

                bool commonFilterJustByArea = loginfo.PerUrls.Contains("/DataPermission/CommonFilterJustByArea");
                string filterCompanyCode = " and al.areaCode like '" + loginfo.AreaCode + "%'";

                string sqlstr = "";
                string notExeDtsqlstr = "";
                //所有
                DataTable notExeDt = new DataTable();
                //待审核
                DataTable exeingDt = new DataTable();
                //审核通过
                DataTable completeDt = new DataTable();
                //审核不通过
                DataTable audiuDt = new DataTable();

                var isOperaterView = false;

                sqlstr = $@" select top {pagesize}  MaintId,GensetNum,MaintPerson,GenRunPeriod,MaintFee,IsAudited,MaintDate
                             FROM Maintenence as al
                          where  al.PrjCode={loginfo.PrjCode}  {filterCompanyCode}  {whereStr2}  and MaintId>{topNum} ";

                //未审核   

                string orderby = " order by al.MaintId ASC";
               

                switch (menuIndex)
                {
                    case 0://所有
                        notExeDt = (sqlstr + "" + orderby).SqlQuery();
                        return new
                        {

                            noExtTotal = notExeDt.Rows.Count,
                            noEx = notExeDt.ToDynamicList()
                        };
                    case 1://待审核
                        exeingDt = (sqlstr + " and IsAudited is null" + orderby).SqlQuery();
                        return new
                        {

                            exingTotal = exeingDt.Rows.Count,
                            exeing = exeingDt.ToDynamicList()
                        };
                    case 2://审核通过
                        completeDt = (sqlstr + " and IsAudited=1 " + orderby).SqlQuery();
                        return new
                        {

                            completelyTotal = completeDt.Rows.Count,
                            completely = completeDt.ToDynamicList()
                        };
                    case 3://审核不通过
                        audiuDt = (sqlstr + " and IsAudited=0 " + orderby).SqlQuery();
                        return new
                        {

                            audiuTotal = audiuDt.Rows.Count,
                            audiu = audiuDt.ToDynamicList()
                        };
                    default://返回空数据
                        return new
                        {
                            audiuTotal = 0,
                            audiu = "[]"
                        };
                }

            }
            catch (Exception ex)
            {

               
                return new ResultModel() { Code = 0, Result = "会话过期"+ex.Message };
            }




        }

        /// <summary>
        /// 添加维修
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("AddGenMain")]
        public async Task<string> AddGenMain([FromForm] Maintenence model)
        {
            try
            {
                var LoginInfo = _workManager.CurrentUser;
                var a = model.MaintFee.GetType();
                List<string> tr = new List<string>();
                if (LoginInfo == null)
                {
                    return "用户信息已失效,请重新登录";
                }
                if (model.GenRunPeriod > 100)
                {
                    //判断油机保养是否有一条没有审核的
                    bool ckGensetNum =await _generatorManager.GetGenMainIsAuditedAnyAsync(model.GensetNum);
                    if (ckGensetNum)
                    {
                        return "此油机存在未审核或审核不通过保养记录";
                    }
                    //Generator Gmodel =  dbContext.Queryable<Generator>().First(i => i.GensetNum == model.GensetNum);
                    Generator Gmodel =MemoryEntity.gBuffGen.All.Values.FirstOrDefault(i => i.GensetNum == model.GensetNum);
                    model.AreaCode = Gmodel.AreaCode;
                    model.AreaName = Gmodel.AreaName;
                    model.MaintPerson = LoginInfo.UserName;
                    model.MaintPersonCode = LoginInfo.UserCode;
                    model.MaintPersonPhone = LoginInfo.UserPhone;
                    model.MaintCompany = LoginInfo.CompanyName;
                    model.CompanyCode = LoginInfo.CompanyCode;
                    model.DTUID = Gmodel.DTUID;
                    model.CreateDate = DateTime.Now;
                    model.CreatePerson = LoginInfo.UserCode;
                    model.PrjCode = LoginInfo.PrjCode;
                    model.PrjName = LoginInfo.PrjName;
                    model.IsAudited = null;
                    var res =await _generatorManager.AddMaintenenceAsync(model);// dbContext.GetSimpleClient<Maintenence>().Insert(model);
                    if (res!= null)
                    {
                        return "添加成功！";
                    }
                    else
                    {
                        return "添加失败！";
                    }
                }
                else
                {
                    return "发电时长不超过100小时！不需要保养";
                }

            }
            catch (Exception ex)
            {
                if (ex.Message == "未将对象引用设置到对象的实例。")
                {
                    return "保养费用只能由数字和小数点组成";
                }
                return "添加失败！";
            }
        }
        #endregion

        #region 采集器维修-与图片

        /// <summary>
        /// 获取油机维修列表数量
        /// </summary>
        /// <param name="times">全部0 一周7 半月15 本月30</param>
        /// <param name="paraStr">搜索</param>
        /// <returns></returns>
        [QueryParameters]
        [HttpGet]
        public dynamic GetMaintainCount(int times, string paraStr)
        {
            try
            {
                UserAccount loginfo = _workManager.CurrentUser; 
                if (loginfo == null)
                    return null;
                var whereStr = 0;
                if (paraStr != "" && paraStr != null)
                    whereStr = 1;//搜索框有内容
                var whereStr2 = (whereStr == 1) ? (" and (al.GensetNum like '%" + paraStr + "%' or DTUID like '%" + paraStr + "%' )") : "";
                if (times == 1)//今天
                {
                    whereStr2 += (" and al.CreateTime BETWEEN CONVERT(varchar(100), GETDATE(), 23) +' 00:00:00' AND CONVERT(varchar(100), GETDATE(), 23) +' 23:59:59' ");
                }
                else if (times == 7)//7天内
                {
                    whereStr2 += (" and DateDiff(dd,al.CreateTime,getdate())<=7  ");
                   }
                else if (times == 30)//本月
                {
                    whereStr2 += (" and  DateDiff(dd,al.CreateTime,getdate())<=30 ");
                }
            
                string sqlstr = "";
                //所有
                DataTable notExeDt = new DataTable();
                //待审核
                DataTable exeingDt = new DataTable();
                //审核通过
                DataTable completeDt = new DataTable();
                //审核不通过
                DataTable audiuDt = new DataTable();




                sqlstr = $" SELECT COUNT(Id) as count FROM CollectorRepair AS al where  al.PrjCode={loginfo.PrjCode}  {whereStr2} ";
                //所有 
                notExeDt = (sqlstr + "").SqlQuery();

                //待审核  
                exeingDt = (sqlstr + " and AuditState=0").SqlQuery();

                //审核通过
                completeDt = (sqlstr + " and (AuditState=1 or AuditState=3) ").SqlQuery();

                //审核不通过
                audiuDt = (sqlstr + " and AuditState=2 ").SqlQuery();

                return new
                {

                    noExtTotal = notExeDt.Rows[0]["count"],
                    exingTotal = exeingDt.Rows[0]["count"],
                    completelyTotal = completeDt.Rows[0]["count"],
                    audiuTotal = audiuDt.Rows[0]["count"],

                };

            }
            catch (Exception ex)
            {
                
                return new ResultModel() { Code = 0, Result = "会话过期" + ex.Message };

            }
        }

        /// <summary>
        /// 获取油机维修列表（分页）
        /// </summary>
        /// <param name="times">全部0 一周7 半月15 本月30</param>
        /// <param name="pagesize">每页多少数据，默认50</param>
        /// <param name="topNum">配合sql语句</param>
        /// <param name="menuIndex">页面tab选项 0：所有 1：待审核 2：审核通过 3：审核不通过</param>
        /// <param name="paraStr">查询条件</param>
        /// <returns></returns>
        [HttpGet]
        [QueryParameters]
        public dynamic GetMaintainListByPage(int times, int pagesize, int topNum, int menuIndex, string paraStr)
        {
               try
            {
         
                var  loginfo =_workManager.CurrentUser;
                if (loginfo == null)
                    return null;
                var whereStr = 0;
                if (paraStr != "" && paraStr != null)
                    whereStr = 1;//搜索框有内容
                var whereStr2 = (whereStr == 1) ? (" and (al.GensetNum like '%" + paraStr + "%' or DTUID like '%" + paraStr + "%' )") : "";
                if (times == 1)//今天
                {
                    whereStr2 += (" and al.CreateTime BETWEEN CONVERT(varchar(100), GETDATE(), 23) +' 00:00:00' AND CONVERT(varchar(100), GETDATE(), 23) +' 23:59:59' ");
                }
                else if (times == 7)//7天内
                {
                    whereStr2 += (" and DateDiff(dd,al.CreateTime,getdate())<=7  ");
                }
                else if (times == 30)//本月
                {
                    whereStr2 += (" and  DateDiff(dd,al.CreateTime,getdate())<=30 ");
                }
             

                string sqlstr = "";
                string notExeDtsqlstr = "";
                //所有
                DataTable notExeDt = new DataTable();
                //待审核
                DataTable exeingDt = new DataTable();
                //审核通过
                DataTable completeDt = new DataTable();
                //审核不通过
                DataTable audiuDt = new DataTable();

                var isOperaterView = false;

                sqlstr = $@" select top {pagesize}  Id,GensetNum,DTUID,CreateTime,RepairerName,AuditState,RepairCode
                             FROM CollectorRepair as al
                          where  al.PrjCode={loginfo.PrjCode} {whereStr2}  and Id>{topNum} ";

                //未审核   

                string orderby = " order by al.Id ASC";


                switch (menuIndex)
                {
                    case 0://所有
                        notExeDt = (sqlstr + "" + orderby).SqlQuery();
                        return new
                        {

                            noExtTotal = notExeDt.Rows.Count,
                            noEx = notExeDt.ToDynamicList()
                        };
                    case 1://待审核
                        exeingDt = (sqlstr + " and AuditState=0 " + orderby).SqlQuery();
                        return new
                        {

                            exingTotal = exeingDt.Rows.Count,
                            exeing = exeingDt.ToDynamicList()
                        };
                    case 2://审核通过
                        completeDt = (sqlstr + " and (AuditState=1 or AuditState=3) " + orderby).SqlQuery();
                        return new
                        {

                            completelyTotal = completeDt.Rows.Count,
                            completely = completeDt.ToDynamicList()
                        };
                    case 3://审核不通过
                        audiuDt = (sqlstr + " and AuditState=2 " + orderby).SqlQuery();
                        return new
                        {

                            audiuTotal = audiuDt.Rows.Count,
                            audiu = audiuDt.ToDynamicList()
                        };
                    default://返回空数据
                        return new
                        {
                            audiuTotal = 0,
                            audiu = "[]"
                        };
                }

            }
            catch (Exception ex)
            {

               
                return new ResultModel() { Code = 0, Result = "会话过期"+ex.Message };
            }

        }
        /// <summary>
        /// 添加维修
        /// </summary>
        /// <param name="GensetNum"></param>
        /// <param name="DTUID"></param>
        /// <param name="RepairContent"></param>
        /// <param name="MaintPicture"></param>
        /// <returns></returns>
        [HttpPost("AddMaintain")]
        public async Task<ResultModel> AddMaintain(string GensetNum, string DTUID, string RepairContent, string[] MaintPicture)
        {
            var LoginInfo = _workManager.CurrentUser;
            ResultModel Result = new ResultModel();
            if (LoginInfo == null)
            {
                Result.Code = 0;
                Result.Result = "会话过期";
                return Result;

            }
            if (LoginInfo.RoleCode != "powermanGZ" && LoginInfo.RoleCode != "dwadminGZ")
            {
                Result.Code = 0;
                Result.Result = "您没有此权限";
                return Result;
            }
            if (await _generatorManager.GetMaintainAnyAsync(DTUID))
            {
                Result.Code = 0;
                Result.Result = "该采集器存在未审核或未维修的工单!";
                return Result;
            }

            Result.Code = 1;
            CollectorRepair CR = new CollectorRepair();

            CR.RepairCode = _generatorManager.GetRepairCode();

            CR.DTUID = DTUID;
            CR.GensetNum = GensetNum;
            CR.RepairContent = RepairContent;
            CR.RepairerCode = LoginInfo.UserCode;
            CR.RepairerName = LoginInfo.UserName;
            CR.RepairerPhone = LoginInfo.UserPhone;
            CR.PrjCode = LoginInfo.PrjCode;
            CR.CreateTime = DateTime.Now;
            CR.AuditState = 0;
            try
            {
                // CR.RepairCount = dbContext.Queryable<CollectorRepair>().Where(x => x.DTUID == CR.DTUID).Count();
                //以反修后数量重及
                var TempData = (await _generatorManager.GetMaintainListAsync(CR.DTUID, 4)).Select(u => u.CreateTime).ToList();
                if (TempData == null || TempData.Count == 0)
                {
                    CR.RepairCount = (await _generatorManager.GetMaintainListAsync(CR.DTUID, 4)).Count();
                }
                else
                {
                    var Tmp = (TempData.Count() + 1) * 100;
                    CR.RepairCount = Tmp + (await _generatorManager.GetMaintainByCreateTimeListAsync(CR.DTUID, TempData[0].Value)).Count(); ;
                }

            }
            catch (Exception)
            {

            }
            var Tempdata = await _generatorManager.AddMaintainAsync(CR);

            if (Tempdata != null)
            {
                foreach (string pr in MaintPicture)
                {
                    try
                    {


                        string Temp = ImageHelper.GetImageFromBase64InToContent(pr.Replace("data:image/jpeg;base64,", ""), CR.RepairCode + "\n" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        Temp = "data:image/jpeg;base64," + Temp;
                        CollectorRepairPicture crp = new CollectorRepairPicture();
                        crp.RepairCode = CR.RepairCode;
                        crp.RepairPicture = Temp;
                        await _generatorManager.AddMaintainPictureAsync(crp);

                    }
                    catch (Exception ex)
                    {

                    }
                }
                Result.Result = CR.RepairCode;
            }
            return Result;
        }
        #endregion

        #region 对机组添加支架--信息

        /// <summary>
        /// 获取油机支架列表数量（分页）方法
        /// </summary>
        /// <param name="times">全部0 一周7 半月15 本月30</param>
        /// <param name="pagesize">每页多少数据，默认50</param>
        /// <param name="topNum">配合sql语句</param>
        /// <param name="menuIndex">页面tab选项 0：全部 1：待审核 2：已审核 3：审核不通过</param>
        /// <param name="paraStr">查询条件</param>
        /// <returns></returns>
        [QueryParameters]
        [HttpGet]
        public dynamic GetBracketListByPage(int times = 0, int pagesize = 50, int topNum = 0, int menuIndex = 0, string paraStr = "")
        {
            var LoginInfo = _workManager.CurrentUser;

            string userCode = LoginInfo.UserCode;
            string PrjCode = LoginInfo.PrjCode;

            var whereStr = 0;
            if (paraStr != "" && paraStr != null)
                whereStr = 1;//搜索框有内容
            var whereStr2 = (whereStr == 1) ? (" and (al.GensetNum like '%" + paraStr + "%' or DTUID like '%" + paraStr + "%' )") : "";
            if (times == 1)//今天
            {
                whereStr2 += (" and al.CreateTime BETWEEN CONVERT(varchar(100), GETDATE(), 23) +' 00:00:00' AND CONVERT(varchar(100), GETDATE(), 23) +' 23:59:59' ");
            }
            else if (times == 7)//7天内
            {
                whereStr2 += (" and DateDiff(dd,al.CreateTime,getdate())<=7  ");
            }
            else if (times == 30)//本月
            {
                whereStr2 += (" and  DateDiff(dd,al.CreateTime,getdate())<=30 ");
            }
            //var isAudit = loginfo.PerUrls.Contains("/Gen/AnnounceTeleAudit/Audit");

            //bool commonFilterJustByArea = loginfo.PerUrls.Contains("/DataPermission/CommonFilterJustByArea");
            //string filterCompanyCode = " and al.areaCode like '" + loginfo.AreaCode + "%'";

            string sqlstr = "";
          
            //所有
            DataTable notExeDt = new DataTable();
            //待审核
            DataTable exeingDt = new DataTable();
            //审核通过
            DataTable completeDt = new DataTable();
            //审核不通过
            DataTable audiuDt = new DataTable();

            

            sqlstr = $@" select top {pagesize}  Id,GensetNum,DTUID,CreateTime,CreateName,AuditState,BracketCode
                             FROM CollectorBracket as al
                          where  al.PrjCode={PrjCode} {whereStr2}  and Id>{topNum} ";

            //未审核   

            string orderby = " order by al.Id ASC";


            switch (menuIndex)
            {
                case 0://所有
                    notExeDt = (sqlstr + "" + orderby).SqlQuery();
                    return new
                    {

                        noExtTotal = notExeDt.Rows.Count,
                        noEx = notExeDt.ToDynamicList()
                    };
                case 1://待审核
                    exeingDt = (sqlstr + " and AuditState=0 " + orderby).SqlQuery(); ;
                    return new
                    {

                        exingTotal = exeingDt.Rows.Count,
                        exeing = exeingDt.ToDynamicList()
                    };
                case 2://审核通过
                    completeDt = (sqlstr + " and (AuditState=1 or AuditState=3) " + orderby).SqlQuery();
                    return new
                    {

                        completelyTotal = completeDt.Rows.Count,
                        completely = completeDt.ToDynamicList()
                    };
                case 3://审核不通过
                    audiuDt = (sqlstr + " and AuditState=2 " + orderby).SqlQuery();
                    return new
                    {

                        audiuTotal = audiuDt.Rows.Count,
                        audiu = audiuDt.ToDynamicList()
                    };
                default://返回空数据
                    return new
                    {
                        audiuTotal = 0,
                        audiu = "[]"
                    };
            }

        }


        /// <summary>
        /// 获取审核统计数量
        /// </summary>
        /// <param name="times">时间</param>
        /// <param name="paraStr">查询条件</param>
        /// <returns></returns>
        [QueryParameters]
        [HttpGet]
        public dynamic GetGenBracketCount(int times = 0, string paraStr = "")
        {
            var LoginInfo = _workManager.CurrentUser;
            string userCode = LoginInfo.UserCode;
            string PrjCode = LoginInfo.PrjCode;

            var whereStr = 0;
            if (paraStr != "" && paraStr != null)
                whereStr = 1;//搜索框有内容
            var whereStr2 = (whereStr == 1) ? (" and (al.GensetNum like '%" + paraStr + "%' or DTUID like '%" + paraStr + "%' )") : "";
            if (times == 1)//今天
            {
                whereStr2 += (" and al.CreateTime BETWEEN CONVERT(varchar(100), GETDATE(), 23) +' 00:00:00' AND CONVERT(varchar(100), GETDATE(), 23) +' 23:59:59' ");
            }
            else if (times == 7)//7天内
            {
                whereStr2 += (" and DateDiff(dd,al.CreateTime,getdate())<=7  ");

            }
            else if (times == 30)//本月
            {
                whereStr2 += (" and  DateDiff(dd,al.CreateTime,getdate())<=30 ");
            }

            string sqlstr = "";
            //所有
            DataTable notExeDt = new DataTable();
            //待审核
            DataTable exeingDt = new DataTable();
            //审核通过
            DataTable completeDt = new DataTable();
            //审核不通过
            DataTable audiuDt = new DataTable();






            sqlstr = $" SELECT COUNT(Id) as count FROM CollectorBracket AS al where  al.PrjCode={PrjCode}  {whereStr2} ";
            //所有 
            notExeDt = (sqlstr + "").SqlQuery();

            //待审核  
            exeingDt = (sqlstr + " and AuditState=0").SqlQuery();

            //审核通过
            completeDt = (sqlstr + " and (AuditState=1 or AuditState=3) ").SqlQuery();

            //审核不通过
            audiuDt = (sqlstr + " and AuditState=2 ").SqlQuery();

            return new
            {

                noExtTotal = notExeDt.Rows[0]["count"],
                exingTotal = exeingDt.Rows[0]["count"],
                completelyTotal = completeDt.Rows[0]["count"],
                audiuTotal = audiuDt.Rows[0]["count"],

            };
        }

        /// <summary>
        /// 添加支架图片
        /// </summary>
        /// <param name="GensetNum">机组编号</param>
        /// <param name="DTUID">DTUID</param>
        /// <param name="remarkContent">备注</param>
        /// <param name="Picture">图片</param>
        /// <returns></returns>
        [HttpPost("AddBracket")]
        public async Task<ResultModel> AddBracket(string GensetNum, string DTUID, string remarkContent, string[] Picture)
        {
            var loginfo = _workManager.CurrentUser;
            ResultModel Result = new ResultModel();
            if (loginfo.RoleCode != "powermanGZ" && loginfo.RoleCode != "dwadminGZ")
            {
                Result.Code = 0;
                Result.Result = "您没有此权限！";
                return Result;
            }
           
            //var repairList = dbContext.Queryable<CollectorBracket>().Where(c => c.DTUID == DTUID && c.AuditState == 0).ToList();
            var repairList =await  _generatorManager.GetCollectorBracketAsync(DTUID,0);
            if (repairList.Count > 0)
            {
                Result.Code = 0;
                Result.Result = "该采集器存在未审核的支架图片！";
                return Result;
            }
               
          
            Result.Code = 1;
            CollectorBracket CR = new CollectorBracket();

            CR.BracketCode = _generatorManager.GetBracketCode();
            CR.DTUID = DTUID;
            CR.GensetNum = GensetNum;
            CR.remarkContent = remarkContent;
            CR.CreateCode = loginfo.UserCode;
            CR.CreateName = loginfo.UserName;
            CR.CreatePhone = loginfo.UserPhone;
            CR.PrjCode = loginfo.PrjCode;
            CR.CreateTime = DateTime.Now;
            CR.AuditState = 0;
            CR.submitCount =await _generatorManager.GetCollectorBracketCountAsync(DTUID) + 1;//提交次数

            var ResultCR = _generatorManager.AddCollectorBracketAsync(CR);
            if (ResultCR != null)
            {
                foreach (string pr in Picture)
                {
                    try
                    {

                        string Temp = ImageHelper.GetImageFromBase64InToContent(pr.Replace("data:image/jpeg;base64,", ""), CR.BracketCode + "\n" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        Temp = "data:image/jpeg;base64," + Temp;
                        CollectorBracketPicture crp = new CollectorBracketPicture();
                        crp.BracketCode = CR.BracketCode;
                        crp.BracketPicture = Temp;
                        // crp.RepairPicture = pr;
                        await _generatorManager.AddCollectorBracketPictureAsync(crp);
                        
                    }
                    catch (Exception ex)
                    {

                    }
                }
                Result.Result = CR.BracketCode;
            }




            return Result;

        }
        #endregion

    }
}
